import 'dart:math';
import 'dart:ui';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:provider/provider.dart';

import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/entity/home/video_list_entity.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';

import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/home/trendVo.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_manager.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../view_model/mine/trend_view_user_model.dart';
import '../../../../wcao/ui/theme.dart';
import 'TrendViewUserModel.dart';


class ImageTrendViewUserPage extends StatefulWidget {
  const ImageTrendViewUserPage({Key? key}) : super(key: key);

  @override
  _PageViewMineState createState() => _PageViewMineState();
}

class _PageViewMineState extends State<ImageTrendViewUserPage> with AutomaticKeepAliveClientMixin<ImageTrendViewUserPage> ,SingleTickerProviderStateMixin{
  TokenController tokenController = Get.find();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    tokenController.getUserInfo();
  }


  @override
  Widget build(BuildContext context) {
    super.build(context); // 重要：调用super.build(context)以保持状态
    return ChangeNotifierProvider(
        create: (BuildContext context) => ImageTrendViewUserModel(),
        child: Consumer<ImageTrendViewUserModel>(
            builder: (context, viewModel, child) {
              ;
              return CustomRefresh(
                 // physics: NeverScrollableScrollPhysics(),

                  isMaterialHeader:true,
                  controller: viewModel.refreshController,
                  enablePullUp: true,
                  onRefresh: () async {
                    viewModel.onRefresh();
                  },
                  onLoading: () async {
                    viewModel.onLoading();
                  },
                  child: SingleChildScrollView(
                    // physics: NeverScrollableScrollPhysics(),
                      child: buildWateFall(viewModel)
                  )


              );
            })
    );


  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

Map<int, double> imagesHeightMap = {};

double getRandomHeight(int index) {
  // 检查imagesHeightMap中是否已经存在对应索引的高度
  if (imagesHeightMap.containsKey(index)) {
    // 如果存在，返回该高度
    return imagesHeightMap[index]!;
  } else {
    // 如果不存在，生成一个新的随机高度并添加到Map中
    double height = Random().nextDouble() * (200 - 80) + 168;
    imagesHeightMap[index] = height;
    return height;
  }
}
buildWateFall(ImageTrendViewUserModel viewModel) {
  TokenController tokenController = Get.find();

  ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
  return MasonryGridView.count(
    padding: EdgeInsets.all(0),
    // 展示几列
    crossAxisCount: 2,
    // 元素总个数
    itemCount: viewModel.datas.length,
    // 单个子元素
    itemBuilder: (BuildContext context, int index) {
      TrendEntity trendEntity = viewModel.datas[index];
      // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
      return GestureDetector(
        onTap: () async {
          // Loader.show(context,
          //     isSafeAreaOverlay: true,
          //
          //     isBottomBarOverlay: true,
          //
          //     overlayColor: Colors.black26,
          //     progressIndicator: SizedBox(
          //       width: 50,
          //       height: 50,
          //       child:  LoadingIndicator(
          //         indicatorType: Indicator.ballScaleMultiple, /// Required, The loading type of the widget
          //         colors:  [Colors.white,WcaoTheme.primary,WcaoTheme.primaryOpacity],       /// Optional, The color collections
          //         strokeWidth: 1,                     /// Optional, The stroke of the line, only applicable to widget which contains line
          //
          //       ),
          //     ),
          //     themeData: Theme.of(context)
          //         .copyWith(colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.green))
          // );
          HudUtil.showBeautiful(context);
          String uid = await tokenController.getUid();
          Map<String,dynamic> params = {
            "mid":trendEntity.mid,
            "uid": uid
          };
          HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
          imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
          await imageDetailVideoController.getImageVideoDetail();
          HudUtil.dismiss();
          Get.toNamed("/ui/home/imageVideoDetail");

        },
        child: Card(
          margin: EdgeInsets.all(1.5),

          child: ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child:  Column(
              children: [
                FancyShimmerImage(
                  height: getRandomHeight(index),
                  imageUrl: trendEntity.cover!,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [

                    Flexible(

                      child: Text(
                        trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                        overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                      ),

                    ),
                    Row(
                      children: [
                        Icon(
                          CupertinoIcons.heart,size: 14,
                          color: Colors.grey,),
                        Text(trendEntity.agreeCount as String)
                      ],
                    )



                  ],
                )

                ,


              ],
            ),
          ),
        ),
      );
    },

    // 纵向元素间距
    mainAxisSpacing: 0,
    // 横向元素间距
    crossAxisSpacing: 0,
    //本身不滚动，让外面的singlescrollview来滚动
    physics:const NeverScrollableScrollPhysics(),
    shrinkWrap: true, //收缩，让元素宽度自适应
  )

  //   WaterfallFlow.builder(
  //   padding: EdgeInsets.all(8.0),
  //   gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
  //     crossAxisCount: 2,
  //
  //     crossAxisSpacing: 5.0,
  //     mainAxisSpacing: 5.0,
  //   ),
  //   itemCount: viewModel.datas.length,
  //   itemBuilder: (BuildContext context, int index) {
  //     TrendEntity trendEntity = viewModel.datas[index];
  //     var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
  //     double height = getRandomHeight();
  //     return Container(
  //       // color: Colors.blue,
  //       height: height,
  //       child: Center(
  //         child: FancyShimmerImage(
  //           height: height-30,
  //           imageUrl: imgsUrl[0],
  //         ),
  //       ),
  //     );
  //   },
  // )
      ;


}
